from django.db import models
from django.contrib.auth.models import AbstractUser
from meiduo_mail.utils.models import BaseModel
from apps.areas.models import Areas

# Create your models here.


class User(AbstractUser):
    """
    由于django自带的User模型类目前还不能满足实际需求，自定义User模型类，添加mobile属性
    django中自带的User模型类在：django.contrib.auth.models中可以查看
    """
    mobile = models.CharField(max_length=11, unique=True)
    email_active = models.BooleanField(default=False, verbose_name='邮箱状态')
    default_address = models.ForeignKey('Address',related_name='users', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='默认地址')

    class Meta:
        db_table = 'tb_users'

    def __str__(self):
        return self.username


class Address(BaseModel):
    """
    关联外键字段中第一个参数：
    1、自关联第一个参数一定是为:'self'
    2、非自关联第一个参数为关联的模型类，有两种写法，方法一：导包把需要关联的模型类导入，然后直接填入类名：例如U
    3、非自关联第一个参数为关联的模型类，有两种写法，方法一：不需要导包，'子应用名.类名'，例如28行
    """
    user = models.ForeignKey(User,related_name='addresses', on_delete=models.CASCADE, verbose_name='用户')
    province = models.ForeignKey('areas.Areas', related_name='province', on_delete=models.PROTECT, verbose_name='省')
    city = models.ForeignKey(Areas, related_name='city', on_delete=models.PROTECT, verbose_name='市')
    district = models.ForeignKey('areas.Areas', related_name='district', on_delete=models.PROTECT, verbose_name='区')
    title = models.CharField(max_length=50, verbose_name='地址名称')
    receiver = models.CharField(max_length=20, verbose_name='收货人')
    place = models.CharField(max_length=50, verbose_name='地址')
    mobile = models.CharField(max_length=11, verbose_name='电话号码')
    tel = models.CharField(max_length=20, null=True, blank=True,verbose_name='固定电话')
    email = models.CharField(max_length=30, null=True, blank=True, verbose_name='邮箱')
    is_delete = models.BooleanField(default=False, verbose_name='物理删除')

    class Meta:
        db_table = 'tb_address'
        # ordering:指定默认的排序规则，如果指定了默认的查询规则，凡是查询集得到的结果都是按照规则排好序的
        # ['update_time']:升序
        # ['-update_time']:降序，最近一次新建或者修改的地址排列在最前面
        ordering = ['-update_time']